// components/FTWindow/FTWindow.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },


    /**
     * 组件的初始数据
     */
    data: {
        timer: 0,

        Enum: {
            Rarity: {
                R: 1,
                SR: 2,
                SSR: 3,
            },
            E_attr: {
                atk: 1,
                dfs: 2,
                HP: 3,
                MP: 4,
            },
            State: {
                nil: 0,
                silent: 1,
                atk_buff: 2,
                dfs_buff: 3,
                bonus: 4,
                atk_debuff: 5,
                dfs_debuff: 6,
                punish: 7,
            },
        },
        canvMaxW: 20,
        canvMaxH: 30,
        Target: 0,//攻击目标
        NowCharacter: 0,//轮到该角色攻击
        last_character: 0,
        // 上场的角色，{ rid,equip } × 6
        is_robot_call: false,
        role_on_battle: [[], []],//上场角色，前一列表为房主上阵角色
        MPisMax: false,//MP满即可释放技能
        Turn: true,//是自己的回合
        IsOwner: true,
        site1: 45,
        site2: 0,
        site3: -270,
        site4: 560,
        site5: 300,
        site6: 280,
        roles: [],
        role: {
            rid: 0,
            rname: "",
            HP: 0,
            atk: 0,
            dfs: 0,
            rarity: 0,
            skill: null,
        },
        skill: {
            dmg_flag: false,
            dmg_to_all: false,  // 群伤
            dmg_ratio: 1.0,
            //cure_falg: false,
            //cure_ratio: 1.0,
            eff_flag: false,
            eff_state: 0,
            eff_to_all: false,   // 群体增益/减益
            eff_timer: 0,
        },

        equipments: [],
        equipment: {
            eid: 0,
            ename: "",
            attr: 0,
            prompt: 1.0,
            description: ""
        },

        roleImpls: [[], []], // 二维列表，2，3
        roleImpl: {
            rid: 0,
            HP: 0,
            MP: 0,
            fullHP: 0,
            fullMP: 0,
            atk: 0,
            dfs: 0,

            get_dmg: false, // 受击
            dmg_val: 0, // 受击数值

            equip: null,
            states: [],  //<state,timer>
            skill: null,
        },

        coin: 0, //金币结算

        game_over: false,
        player1win: false,   //房主player1

        hpRectX0: [0, 0, 0, 0, 0, 0],
        hpRectY0: [0, 0, 0, 0, 0, 0],

        mpRectX0: [0, 0, 0, 0, 0, 0],
        mpRectY0: [0, 0, 0, 0, 0, 0],

        stickH: 3,
        timer_robot:0,

    },


    /**
     * 组件的方法列表
     */
    methods: {
        setIsOwner(value) {
            this.data.IsOwner = value;
            if (value) {
                wx.showToast({
                    title: '你是房主',
                    icon: 'none'
                });
            }
        },

        setBarrier(value) {
            this.data.Barrier = value;
            if (value) {
                wx.showToast({
                    title: value,
                    icon: 'none'
                });
            }
        },

        setIsRobot(value) {
            this.data.IsRobot = value;
            if (value) {
                wx.showToast({
                    title: '单机游戏',
                    icon: 'none'
                });
            }
            this.initData();
        },

        setTarget(e) {//选择攻击对象响应
            this.setData({ TgChoose: e.detail.value });
            console.log("已选择敌方", this.data.TgChoose, "号位为攻击对象");
        },

        sleep: function (delay) {
            var start = (new Date()).getTime();
            while ((new Date()).getTime() - start < delay) {
                continue;
            }
        },

        autoSelectTarget: function () {
            if (!this.data.IsRobot) return;
            var minv = 999999999, minT = 0;
            for (var i = 0; i < 3; ++i)
                if (this.data.roleImpls[0][i].HP <= 0)
                    continue;
                else if (minv > this.data.roleImpls[0][i].HP)
                    minv = this.data.roleImpls[0][i].HP, minT = i;
            this.data.Target = minT + 1;
        },

        autoAtk: function () {
            while (this.data.game_over == false && this.data.Turn == false) {
                // 目标选择
                this.autoSelectTarget();
                if (this.data.roleImpls[1][this.data.NowCharacter - 1].MP >= 100)
                    this.execSkiAtk();
                else this.execNorAtk();
              
                this.data.Turn=false;
                this.roundShift();
            }
        },
        

        Attack(e) {//攻击按钮响应
            console.log(e.target.id);
            // console.log("In Component,IsOwner:",this.data.IsOwner);

            var value = e.target.id;
            if (this.data.IsOwner) {
                if (this.data.Turn) {
                    this.setData({ Target: this.data.TgChoose });
                    if (this.data.Target < 4) {
                        if (value == "Skill") {
                            console.log("技能");
                            this.execSkiAtk();
                            this.skillButtonEnable();
                            this.roundShift();
                            this.setData({ game_over: this.data.game_over });
                            
                            if (this.data.IsRobot)
                                setTimeout(() => this.autoAtk(), 1000);
                            else
                                this.triggerEvent('AttackAnother', { data: this.data });


                            this.gameEnding();
                            //执行响应
                        } else if (value == "Normal") {
                            console.log("普攻");
                            this.execNorAtk();
                            this.skillButtonEnable();
                            this.roundShift();
                            this.setData({ game_over: this.data.game_over });
                            if (this.data.IsRobot)
                                setTimeout(() => this.autoAtk(), 1000);
                            else
                                this.triggerEvent('AttackAnother', { data: this.data });

                            this.gameEnding();
                            //执行响应
                        }
                    }
                }
            } else {
                this.setData({ Target: this.data.TgChoose });
                if (!this.data.Turn) {
                    if (this.data.Target < 4) {
                        if (value == "Skill") {
                            console.log("技能");
                            this.execNorAtk();
                            this.skillButtonEnable();
                            this.roundShift();
                            this.setData({ game_over: this.data.game_over });
                            this.triggerEvent('AttackAnother', { data: this.data });
                            this.gameEnding();
                            //执行响应
                        } else if (value == "Normal") {
                            console.log("普攻");
                            this.execNorAtk();
                            this.skillButtonEnable();
                            this.roundShift();
                            this.setData({ game_over: this.data.game_over });
                            this.triggerEvent('AttackAnother', { data: this.data });
                            this.gameEnding();

                            //执行响应
                        }
                    }
                }
            }


        },
        initData() {
            //初始化画布
            console.log("初始化画布");
            var mC1 = this.data.mC1;
            var mC2 = this.data.mC2;
            var mC3 = this.data.mC3;
            var eC1 = this.data.eC1;
            var eC2 = this.data.eC2;
            var eC3 = this.data.eC3;

            var siteW = this.data.canvMaxW;
            var siteH = this.data.canvMaxH;

            // mC1.fillText("mC1", siteW * 1 / 5, siteH * 2 / 10);
            // mC2.fillText("mC2", siteW * 1 / 5, siteH * 5 / 10);
            // mC3.fillText("mC3", siteW * 1 / 5, siteH * 8 / 10);
            // eC1.fillText("eC1", siteW * 3 / 4, siteH * 2 / 10);
            // eC2.fillText("eC2", siteW * 3 / 4, siteH * 5 / 10);
            // eC3.fillText("eC3", siteW * 3 / 4, siteH * 8 / 10);

            //战斗逻辑初始化


            console.log("战斗逻辑初始化");
            this.gameInit();
        },

        //战斗逻辑
        rewardSettle: function (player) {
          //console.log(this.data.game_over);
            var coin = 0;
            for (var i = 0; i < 2; ++i)
                for (var j = 0; j < 3; ++j) {
                    if (this.data.roleImpls[i][j].HP <= 0)
                        continue;
                    coin += this.data.roleImpls[i][j].HP;
                }
            if (player == 1 && !player1win || player == 2 && player1win)
                coin = Math.floor(coin / 2);

            this.data.coin = coin;
        },

        equipAssign: function (eid, ename, description, attr, prompt) {
            this.data.equipments.push({
                eid, ename, attr, prompt, description
            });
        },

        skillConstruct: function (dmg_flag, dmg_to_all, dmg_ratio, eff_flag, eff_state, eff_to_all, eff_timer) {
            return {
                dmg_flag, dmg_to_all, dmg_ratio, eff_flag, eff_state, eff_to_all, eff_timer
            };
        },

        roleAssign: function (rid, rname, HP, atk, dfs, rarity, skill) {
            this.data.roles.push({
                rid, rname, HP, atk, dfs, rarity, skill
            });
        },

        /*
         * 初始化技能、装备、基础角色
         */
        roleInfoInit: function () {
            // 法师
            var ski_wizard = this.skillConstruct(true, true, 0.7, true, this.data.Enum.State.punish, true, 2);
            this.roleAssign(1, "wizard", 6000, 115, 75, this.data.Enum.Rarity.SR, ski_wizard);
            // 镰刀
            var ski_sickle = this.skillConstruct(true, false, 2.5, true, this.data.Enum.State.dfs_debuff, false, 2);
            this.roleAssign(2, "sickle", 8000, 125, 85, this.data.Enum.Rarity.SSR, ski_sickle);
            // 剑客
            var ski_sword = this.skillConstruct(true, false, 1.5, true, this.data.Enum.State.atk_buff, false, 2);
            this.roleAssign(3, "sword", 8000, 100, 100, this.data.Enum.Rarity.SR, ski_sword);
            // 武术
            var ski_master = this.skillConstruct(true, false, 2.0, true, this.data.Enum.State.silent, false, 1);
            this.roleAssign(4, "master", 9000, 100, 90, this.data.Enum.Rarity.SSR, ski_master);
            // 盾兵
            var ski_shield = this.skillConstruct(true, false, 1.0, true, this.data.Enum.State.dfs_buff, true, 3);
            this.roleAssign(5, "shield", 7500, 75, 125, this.data.Enum.Rarity.R, ski_shield);
            // 大锤
            var ski_hammer = this.skillConstruct(true, true, 1.1, false, 0, false, 0);
            this.roleAssign(6, "hammer", 9500, 105, 80, this.data.Enum.Rarity.R, ski_hammer);
            // 手枪
            var ski_pistol = this.skillConstruct(true, false, 2.0, false, 0, false, 0);
            this.roleAssign(7, "pistol", 7000, 120, 75, this.data.Enum.Rarity.R, ski_pistol);
            /*
             * 神奇妙妙装备
             */
            // 剑客的装备
            this.equipAssign(1, "古锭刀", "若敢来犯，必叫你大败而归", this.data.Enum.E_attr.atk, 1.25);
            // 镰刀哥装备
            this.equipAssign(2, "镰刀哥的燕双鹰", "双刀会给出答案", this.data.Enum.E_attr.MP, 30);
            // 法师
            this.equipAssign(3, "奇异博士的小棉袄", "你以为穿上马甲我就不认识你了", this.data.Enum.E_attr.HP, 1500);
            // 大锤
            this.equipAssign(4, "锤哥的拉风头巾", "八十，八十......", this.data.Enum.E_attr.MP, 30);
            // 武术家
            this.equipAssign(5, "大师的雷电之力套装", "能力越大，责任越大。", this.data.Enum.E_attr.dfs, 1.2);

        },

        /*
         * 上场角色信息载入
         */
        roleOnBattleInit: function () {
            var rid = 0;
            var equi = null;

            rid = 3, equi = this.data.equipments[0];
            this.data.role_on_battle[0].push({ rid, equi });
            rid = 2, equi = this.data.equipments[1];
            this.data.role_on_battle[0].push({ rid, equi });
            rid = 5, equi = null;
            this.data.role_on_battle[0].push({ rid, equi });

            rid = 6, equi = this.data.equipments[3];
            this.data.role_on_battle[1].push({ rid, equi });
            rid = 4, equi = this.data.equipments[4];
            this.data.role_on_battle[1].push({ rid, equi });
            rid = 1, equi = null;
            this.data.role_on_battle[1].push({ rid, equi });

        },

        roleImplInit: function () {
            //console.log("roleImplInit");
            this.roleOnBattleInit();
            for (var i = 0; i < 2; ++i)
                this.data.roleImpls[i].splice(0, 3);
            for (var i = 0; i < 2; ++i)
                for (var j = 0; j < 3; ++j) {

                    var roleImpl = {};
                    Object.assign(roleImpl, this.data.roleImpl);

                    roleImpl.rid = this.data.role_on_battle[i][j].rid;
                    roleImpl.fullMP = 100;
                    // roleImpl.MP=0;
                    roleImpl.equip = this.data.role_on_battle[i][j].equip;
                    roleImpl.HP = roleImpl.fullHP = this.data.roles[roleImpl.rid - 1].HP;
                    roleImpl.atk = this.data.roles[roleImpl.rid - 1].atk;
                    roleImpl.dfs = this.data.roles[roleImpl.rid - 1].dfs;
                    roleImpl.skill = this.data.roles[roleImpl.rid - 1].skill;
                    roleImpl.MP = 0;

                    if (roleImpl.equip != null) {
                        if (roleImpl.equip.attr == this.data.Enum.E_attr.atk)
                            roleImpl.atk *= roleImpl.equip.prompt;
                        else if (roleImpl.equip.attr == this.data.Enum.E_attr.dfs)
                            roleImpl.dfs *= roleImpl.equip.prompt;
                        else if (roleImpl.equip.attr == this.data.Enum.E_attr.HP)
                            roleImpl.HP = roleImpl.fullHP = roleImpl.HP + roleImpl.equip.prompt;
                        else if (roleImpl.equip.attr == this.data.Enum.E_attr.MP)
                            roleImpl.MP += roleImpl.equip.prompt;
                    }

                    this.data.roleImpls[i].push(roleImpl);
                }
        },

        cptStickLoc: function () {
            this.data.hpRectX0[0] = this.data.canvMaxW * 1 / 10;
            this.data.hpRectX0[1] = this.data.canvMaxW * 1 / 4;
            this.data.hpRectX0[2] = this.data.canvMaxW * 1 / 10;
            this.data.hpRectX0[3] = this.data.canvMaxW * 4 / 5;
            this.data.hpRectX0[4] = this.data.canvMaxW * 13 / 20;
            this.data.hpRectX0[5] = this.data.canvMaxW * 4 / 5;

            this.data.hpRectY0[0] = this.data.canvMaxH * 3 / 10 - 1;
            this.data.hpRectY0[1] = this.data.canvMaxH * 6 / 10 + 3;
            this.data.hpRectY0[2] = this.data.canvMaxH * 9 / 10 + 8;
            this.data.hpRectY0[3] = this.data.canvMaxH * 3 / 10 - 1;
            this.data.hpRectY0[4] = this.data.canvMaxH * 6 / 10 + 3;
            this.data.hpRectY0[5] = this.data.canvMaxH * 9 / 10 + 8;

            this.data.mpRectX0[0] = this.data.canvMaxW * 1 / 10;
            this.data.mpRectX0[1] = this.data.canvMaxW * 1 / 4;
            this.data.mpRectX0[2] = this.data.canvMaxW * 1 / 10;
            this.data.mpRectX0[3] = this.data.canvMaxW * 4 / 5;
            this.data.mpRectX0[4] = this.data.canvMaxW * 13 / 20;
            this.data.mpRectX0[5] = this.data.canvMaxW * 4 / 5;

            this.data.mpRectY0[0] = this.data.canvMaxH * 3 / 10 + 3;
            this.data.mpRectY0[1] = this.data.canvMaxH * 6 / 10 + 7;
            this.data.mpRectY0[2] = this.data.canvMaxH * 9 / 10 + 12;
            this.data.mpRectY0[3] = this.data.canvMaxH * 3 / 10 + 3;
            this.data.mpRectY0[4] = this.data.canvMaxH * 6 / 10 + 7;
            this.data.mpRectY0[5] = this.data.canvMaxH * 9 / 10 + 12;
        },

        ImageInit() {
            if (this.data.IsRobot) {//单机
                switch (this.data.Barrier) {
                    case "一关":
                        this.setData({ mC1Image: "../../assets/role/121.png" })
                        this.setData({ mC2Image: "../../assets/role/421.png" })
                        this.setData({ mC3Image: "../../assets/role/521.png" })
                        this.setData({ eC1Image: "../../assets/role/322.png" })
                        this.setData({ eC2Image: "../../assets/role/212.png" })
                        this.setData({ eC3Image: "../../assets/role/622.png" })
                        this.setData({ FTBG: "../../assets/BG/荒山.png" })
                        
                        break;
                    case "二关":
                        this.setData({ mC1Image: "../../assets/role/721.png" })
                        this.setData({ mC2Image: "../../assets/role/321.png" })
                        this.setData({ mC3Image: "../../assets/role/421.png" })
                        this.setData({ eC1Image: "../../assets/role/222.png" })
                        this.setData({ eC2Image: "../../assets/role/522.png" })
                        this.setData({ eC3Image: "../../assets/role/122.png" })
                        this.setData({ FTBG: "../../assets/BG/荒雪原.png" })
                        break;
                    case "三关":
                        this.setData({ mC1Image: "../../assets/role/621.png" })
                        this.setData({ mC2Image: "../../assets/role/321.png" })
                        this.setData({ mC3Image: "../../assets/role/221.png" })
                        this.setData({ eC1Image: "../../assets/role/322.png" })
                        this.setData({ eC2Image: "../../assets/role/722.png" })
                        this.setData({ eC3Image: "../../assets/role/622.png" })
                        this.setData({ FTBG: "../../assets/BG/村庄.png" })
                        break;
                    case "四关":
                        this.setData({ mC1Image: "../../assets/role/121.png" })
                        this.setData({ mC2Image: "../../assets/role/221.png" })
                        this.setData({ mC3Image: "../../assets/role/321.png" })
                        this.setData({ eC1Image: "../../assets/role/422.png" })
                        this.setData({ eC2Image: "../../assets/role/522.png" })
                        this.setData({ eC3Image: "../../assets/role/622.png" })
                        this.setData({ FTBG: "../../assets/BG/遗弃的村庄.png" })
                        break;
                    case "五关":
                        this.setData({ mC1Image: "../../assets/role/721.png" })
                        this.setData({ mC2Image: "../../assets/role/221.png" })
                        this.setData({ mC3Image: "../../assets/role/521.png" })
                        this.setData({ eC1Image: "../../assets/role/422.png" })
                        this.setData({ eC2Image: "../../assets/role/622.png" })
                        this.setData({ eC3Image: "../../assets/role/322.png" })
                        this.setData({ FTBG: "../../assets/BG/凯旋城.png" })
                        break;
                    case "六关":
                        this.setData({ mC1Image: "../../assets/role/121.png" })
                        this.setData({ mC2Image: "../../assets/role/521.png" })
                        this.setData({ mC3Image: "../../assets/role/721.png" })
                        this.setData({ eC1Image: "../../assets/role/622.png" })
                        this.setData({ eC2Image: "../../assets/role/222.png" })
                        this.setData({ eC3Image: "../../assets/role/422.png" })
                        this.setData({ FTBG: "../../assets/BG/风铃草原.png" })
                        break;
                }

            } else {//联机
                this.setData({ mC1Image: "../../assets/role/721.png" })
                this.setData({ mC2Image: "../../assets/role/421.png" })
                this.setData({ mC3Image: "../../assets/role/521.png" })
                this.setData({ eC1Image: "../../assets/role/322.png" })
                this.setData({ eC2Image: "../../assets/role/212.png" })
                this.setData({ eC3Image: "../../assets/role/622.png" })
                this.setData({ FTBG: "../../assets/BG/龙门.png" })
              }
        },


        gameInit: function () {
            this.ImageInit();
            this.roleInfoInit();
            this.roleImplInit();
            this.data.NowCharacter = 1;
            this.data.game_over = false;
            this.data.Turn = true;
            this.cptStickLoc();
            this.drawHPMP();
        },

        /*
         * 切换轮次，同时判断游戏结束
         */
        roundShift: function () {
            if(this.data.game_over)  return;
            this.data.last_character = this.data.NowCharacter;
            var i = this.data.Turn ? 0 : 1;
            var j = this.data.NowCharacter - 1;
            var k = 1 - i;
            this.data.game_over = true;
            for (var l = 0; l < 3; ++l)
                if (this.data.roleImpls[k][l].HP > 0) {
                    this.data.game_over = false;
                    break;
                }
            if (this.data.game_over) {
                this.data.NowCharacter = 0;
                this.setData({NowCharacter:0});
                //console.log("66666666");
                this.rewardSettle();
                this.gameEnding();
                return;
            }   
            else if (i == 0)  // 房主回合
                if (this.data.roleImpls[k][j].HP > 0)
                    this.data.Turn = false;
                else {
                    j = (j + 1) % 3;
                    for (var l = 0; l < 2; ++l, j = (j + 1) % 3)
                        if (this.data.roleImpls[i][j].HP > 0) {
                            this.setData({ NowCharacter: (j + 1) });
                            break;
                        }
                        else if (this.data.roleImpls[k][j].HP > 0) {
                            this.setData({ NowCharacter: (j + 1) });
                            this.data.Turn = false;
                            break;
                        }
                }
            else {
                j = (j + 1) % 3;
                for (var l = 0; l < 2; ++l, j = (j + 1) % 3)
                    if (this.data.roleImpls[i][j].HP > 0) {
                        this.setData({ NowCharacter: (j + 1) });
                        this.data.Turn = true;
                        break;
                    }
                    else if (this.data.roleImpls[k][j].HP > 0) {
                        this.setData({ NowCharacter: (j + 1) });
                        break;
                    }
            }
        },

        skillButtonEnable: function () {
            var i = this.data.Turn ? 0 : 1;
            var j = this.data.NowCharacter - 1;
            this.data.MPisMax = (this.data.roleImpls[i][j].MP >= this.data.roleImpls[i][j].fullMP);
            this.setData({ MPisMax: this.data.MPisMax });
        },

        silentCheck: function () {
            var i = this.data.Turn - 1;
            var j = this.data.NowCharacter - 1;
            for (var k = 0; k < this.data.roleImpls[i][j].states.length; ++k)
                if ((this.data.roleImpls[i][j].states)[k] == this.data.Enum.State.silent)
                    return true;
            return false;
        },

        execStateTimer: function () {
            var player = this.data.Turn ? 0 : 1;
            var len = this.data.roleImpls[player][this.data.NowCharacter - 1].states.length;
            var tmp_state = {
                state: this.data.Enum.State.nil,
                timer: 0,
            };
            for (var i = 0; i < len; ++i) {
                tmp_state = this.data.roleImpls[player][this.data.NowCharacter - 1].states.shift();
                if (tmp_state.timer < 2)
                    continue;
                else {
                    --tmp_state.timer;
                    this.data.roleImpls[player][this.data.NowCharacter - 1].states.push(tmp_state);
                }
            }

        },

        max: function (a, b) { return a > b ? a : b; },
        min: function (a, b) { return a < b ? a : b; },

        execNorAtk: function () {   // 普通攻击
            var i = this.data.Turn ? 0 : 1;
            var k = 1 - i;
            var j = this.data.NowCharacter - 1;
            var l = this.data.Target - 1;

            // 攻击方
            this.data.roleImpls[i][j].MP = this.min(100, this.data.roleImpls[i][j].MP + 40);
            // 受击方
            var dmg_base = this.data.roleImpls[i][j].atk - this.data.roleImpls[k][l].dfs / 5;
            var dmg = dmg_base * 10 + Math.floor(Math.random() * 700) - 350 + 500;

            for (var p = 0; p < this.data.roleImpls[i][j].states.length; ++p)
                switch ((this.data.roleImpls[i][j].states)[p].state) {
                    case this.data.Enum.State.atk_buff:
                        dmg *= 1.15;
                        break;
                    case this.data.Enum.State.atk_debuff:
                        dmg *= 0.8;
                        break;
                    case this.data.Enum.State.bonus:
                        dmg *= 1.1;
                        break;
                    case punish:
                        dmg *= 0.9;
                        break;
                    default:
                        break;
                }

            for (var p = 0; p < this.data.roleImpls[k][l].states.length; ++p)
                switch ((this.data.roleImpls[k][l].states)[p].state) {
                    case this.data.Enum.State.dfs_debuff:
                        dmg *= 1.2;
                        break;
                    case this.data.Enum.State.dfs_buff:
                        dmg *= 0.75;
                        break;
                    case this.data.Enum.State.bonus:
                        dmg *= 0.9;
                        break;
                    case this.data.Enum.State.punish:
                        dmg *= 1.1;
                        break;
                    default:
                        break;
                }

            dmg = Math.floor(dmg);
            for (i = 0; i < 2; ++i)
                for (j = 0; j < 3; ++j)
                    this.data.roleImpls[i][j].get_dmg = false;
            this.data.roleImpls[k][l].get_dmg = true;
            this.data.roleImpls[k][l].dmg_val = dmg;
            this.data.roleImpls[k][l].HP = this.max(0, this.data.roleImpls[k][l].HP - dmg);
            console.log("角色", l + 1, "受到伤害", dmg, "，剩余血量%", this.data.roleImpls[k][l].HP, "\n");
            this.dmgDisplay(k, l, dmg);
        },

        execSkiAtk: function () {     // 技能攻击
            var i = this.data.Turn ? 0 : 1;
            var k = 1 - i;
            var j = this.data.NowCharacter - 1;
            var l = this.data.Target - 1;
            // 攻击方
            this.data.roleImpls[i][j].MP = 0;
            // 受击方
            if (!this.data.roleImpls[i][j].skill.dmg_flag)
                return;

            var dmg_base = this.data.roleImpls[i][j].atk - this.data.roleImpls[k][l].dfs / 5;
            var dmg = dmg_base * 10 + 800;

            for (var p = 0; p < this.data.roleImpls[i][j].states.length; ++p)
                switch ((this.data.roleImpls[i][j].state)[p].state) {
                    case this.data.Enum.State.atk_buff:
                        dmg *= 1.15;
                        break;
                    case this.data.Enum.State.atk_debuff:
                        dmg *= 0.8;
                        break;
                    case this.data.Enum.State.bonus:
                        dmg *= 1.1;
                        break;
                    case punish:
                        dmg *= 0.9;
                        break;
                    default:
                        break;
                }

            dmg *= this.data.roleImpls[i][j].skill.dmg_ratio;

            for (var p = 0; p < 2; ++p)
                for (var q = 0; q < 3; ++q)
                    this.data.roleImpls[p][q].get_dmg = false;
            if (this.data.roleImpls[i][j].skill.dmg_to_all == false) {
                this.data.roleImpls[k][l].get_dmg = true;
                this.data.roleImpls[k][l].dmg_val = Math.floor((dmg + Math.random() * 900 - 450) * 90 / this.data.roleImpls[k][l].dfs);
                this.data.roleImpls[k][l].HP = this.max(0, this.data.roleImpls[k][l].HP - dmg);
                console.log("角色", l + 1, "受到伤害", dmg, "，剩余血量%", this.data.roleImpls[k][l].HP, "\n");
                this.dmgDisplay(k, l, dmg);
            }
            else for (j = 0; j < 2; ++j) {
                this.data.roleImpls[k][j].get_dmg = true;
                this.data.roleImpls[k][j].dmg_val = Math.floor((dmg + Math.random() * 900 - 450) * 90 / this.data.roleImpls[k][j].dfs);
                this.data.roleImpls[k][j].HP = this.max(0, this.data.roleImpls[k][j].HP - dmg);
                console.log("角色", j + 1, "受到伤害", dmg, "，剩余血量%", this.data.roleImpls[k][j].HP, "\n");
                this.dmgDisplay(k, j, dmg);
            }

        },

        passiveMsgResp: function (msg) {
            if (msg.data == undefined || msg.data.data != undefined) {
                wx.showToast({
                    title: '数据层级错误',
                    icon: "error"
                })
            }
            this.data.Turn = msg.data.Turn;
            this.data.NowCharacter = msg.data.NowCharacter;
            this.data.Target = msg.data.Target;
            this.data.game_over = msg.data.game_over;
            this.data.player1win = msg.data.player1win;
            if (this.data.player1win && this.data.IsOwner || (!this.data.player1win && !this.data.IsOwner))
                this.data.coin = 2 * msg.data.coin;
            else this.data.coin = Math.floor(msg.data.coin / 2);

            var i = this.data.IsOwner ? 0 : 1;
            for (var j = 0; j < 3; ++j)
                if (this.data.roleImpls[i][j].HP != msg.data.roleImpls[i][j].HP) {
                    var dmg = this.data.roleImpls[i][j].HP - msg.data.roleImpls[i][j].HP;
                    console.log("我方的", j, "号角色受到了敌方", msg.data.last_character, "号角色造成的", dmg, "点伤害。");
                    this.dmgDisplay(i, j, dmg);
                }

            for (var i = 0; i < 2; ++i)
                for (var j = 0; j < 3; ++j)
                    this.data.roleImpls[i][j] = msg.data.roleImpls[i][j];
        },

        addCoin(value){
          var coin=0;
          wx.getStorage({
            key: 'coins',
            success: function(res) {
              console.log('该用户为老用户，金币为：', res.data);
              coin=value+res.data;
            },
            fail: function() {
              coin=coin+value;
            }
          });
          wx.setStorage({key:"coins",data:coin});
        },

        gameEnding: function () {
           //console.log(this.data.game_over);
            var cn=this.data.coin; 
            cn=cn/200;
            cn=Math.floor(cn);
            var msg = {
                title: '游戏结束',
                content: "胜利！您获得金币"+cn+"个！",
                showCancel: true,
            };
            this.addCoin(cn);
            if (this.data.player1win && this.data.IsOwner || (!this.data.player1win && !this.data.IsOwner))
                msg.content = "您" + msg.content;
            else msg.content = "对方" + msg.content;
            if (this.data.game_over)
                wx.showModal(msg);
        },

        dmg_move: function (ctx, x, y, dmg) {
            ctx.clearRect(0, 0, this.data.canvMaxW, this.data.canvMaxH);
            if (this.data.timer < 40) {
                this.data.timer++;
                ctx.strokeText("-" + dmg, x, y - 0.2 * this.data.timer);
                return true;
            }
            ctx.clearRect(0, 0, this.data.canvMaxW, this.data.canvMaxH);
            clearInterval(this.interval);
            return false;
        },

        //dmg_move_robot: function (ctx, x, y, dmg) {
        //    if (this.data.timer_robot < 40)
        //        return;
        //    else if(this.data.timer_robot < 80) {
        //        ctx.clearRect(0, 0, this.data.canvMaxW, this.data.canvMaxH);
        //        this.data.timer++;
        //        ctx.strokeText("-" + dmg, x, y - 0.2 * this.data.timer);
        //        return true;
        //    }
        //    ctx.clearRect(0, 0, this.data.canvMaxW, this.data.canvMaxH);
        //    clearInterval(this.interval);
        //    return false;
        //},

        dmgDisplay: function (i, j, dmg) {
            var ctx = this.data.eC3;

            var siteW = this.data.canvMaxW;
            var siteH = this.data.canvMaxH;

            ctx.font = "20px Verdana";
            var gradient = ctx.createLinearGradient(0, 0, siteW, 0);
            gradient.addColorStop("0", "red");
            gradient.addColorStop("0.5", "#FF911C");
            gradient.addColorStop("1.0", "#FEFF9F");
            ctx.strokeStyle = gradient;

            var x;
            var y;

            if (i == 0) x = siteW * 1 / 5;
            else x = siteW * 4 / 7;
            y = siteH * (2 + 3 * j) / 10 - 3;

            ctx.strokeText("-" + dmg, x, y);
            this.data.timer = 0;
            this.interval = setInterval(() => this.dmg_move(ctx, x, y, dmg), 17);
            
            this.drawHPMP();
        },

        getData: function () {
            return this.data;
        },

        drawHPMP: function () {
            var hpc = this.data.eC2;
            var mpc = this.data.eC1;
            hpc.clearRect(0, 0, this.data.canvMaxW, this.data.canvMaxH);
            mpc.clearRect(0, 0, this.data.canvMaxW, this.data.canvMaxH);

            var hpX0 = this.data.hpRectX0;
            var hpY0 = this.data.hpRectY0;

            var mpX0 = this.data.mpRectX0;
            var mpY0 = this.data.mpRectY0;      

            var h = this.data.stickH;
            var d;

            for (var i = 0; i < 6; ++i) {
                d = this.data.canvMaxW / 7;
                hpc.fillStyle = 'white';
                hpc.fillRect(hpX0[i], hpY0[i], d, h);
                hpc.fill();

                d = d * this.data.roleImpls[Math.floor(i / 3)][i % 3].HP / this.data.roleImpls[Math.floor(i / 3)][i % 3].fullHP;
                hpc.fillStyle = 'red';
                hpc.fillRect(hpX0[i], hpY0[i], d, h);
                hpc.fill();

                d = this.data.canvMaxW / 7;
                mpc.fillStyle = 'white';
                mpc.fillRect(mpX0[i], mpY0[i], d, h);
                mpc.fill();

                mpc.fillStyle = 'blue';
                d = d * this.data.roleImpls[Math.floor(i / 3)][i % 3].MP / 100;
                mpc.fillRect(mpX0[i], mpY0[i], d, h);
                mpc.fill();
            }

        },
    },


    lifetimes: {//初始化
        ready() {
            var info = wx.getSystemInfoSync();
            var canvW = info.windowWidth - 2;
            var canvH = canvW - 64;
            // var bMaxH = info.windowHeight - canvH - 20;
            this.setData({
                'canvMaxW': canvW,
                'canvMaxH': canvH,
                // 'backbarMaxH': bMaxH
            });

            this.setData({ MyFetchList: [1, 2, 3] });//初始化选择队列
            this.setData({ EnemyFetchList: [1, 2, 3] });
            //动画制作
            console.log("开始实例化动画");

            let taskList = ['mC1', 'mC2', 'mC3', 'eC1', 'eC2', 'eC3'].map((id) => {
                return new Promise((resolve, reject) => {
                    wx.createSelectorQuery().in(this).select('#' + id).fields({ size: true, node: true }, function (res) {
                        res.node.width = res.width;
                        res.node.height = res.height;
                        resolve({
                            width: res.width,
                            height: res.height,
                            canvas: res.node,
                            context: res.node.getContext('2d')
                        })
                    }).exec();
                })
            });
            Promise.all(taskList).then(res => {
                this.data.mC1 = res[0].context;
                this.data.mC2 = res[1].context;
                this.data.mC3 = res[2].context;
                this.data.eC1 = res[3].context;
                this.data.eC2 = res[4].context;
                this.data.eC3 = res[5].context;
                this.data.canvasInitRes = res;
                this.triggerEvent('ready', {});

                var mC1 = this.data.mC1;
                var mC2 = this.data.mC2;
                var mC3 = this.data.mC3;
                var eC1 = this.data.eC1;
                var eC2 = this.data.eC2;
                var eC3 = this.data.eC3;

                var siteW = this.data.canvMaxW;
                var siteH = this.data.canvMaxH;

                // mC1.fillText("mC1", siteW * 1 / 5, siteH * 2 / 10);
                // mC2.fillText("mC2", siteW * 1 / 5, siteH * 5 / 10);
                // mC3.fillText("mC3", siteW * 1 / 5, siteH * 8 / 10);
                // eC1.fillText("eC1", siteW * 3 / 4, siteH * 2 / 10);
                // eC2.fillText("eC2", siteW * 3 / 4, siteH * 5 / 10);
                // eC3.fillText("eC3", siteW * 3 / 4, siteH * 8 / 10);
                //战斗逻辑初始化
                console.log("战斗逻辑初始化");
                console.log(this);

                this.gameInit();
                console.log("In Component,IsOwner:", this.data.IsOwner);
                // if(this.data.IsOwner){}


            });


        }
    }
})
